# -*- coding:utf-8 -*-
# 北梦测教育
# 课程咨询加微信：xiaobeiceshi
# pip install ddddocr
import os
import ddddocr
import base64
import requests
import jsonpath


def get_auth_captcha():
    """获取验证码的接口"""
    payload = {
        "method":"get",
        "url":os.environ["URL"] + "/auth/captcha"
    }
    response = requests.request(**payload).json()
    sn = jsonpath.jsonpath(response,"$..sn")[0]
    image = jsonpath.jsonpath(response,'$..image')[0]
    return sn,image

def dddd_ocr_text(image):
    # 步骤1.需要对image进行分割，得到头部和Base64编码的部分
    encode_data = image.split(",")[1]

    # 步骤2：解码Base64元数据
    decode_data = base64.b64decode(encode_data)

    # 步骤3：通过ddddocr来识别图片元数据
    ocr = ddddocr.DdddOcr()     # 实例化
    text = ocr.classification(decode_data)
    return text

# 存放全局的验证码文本和sn文本
sn_captcha_text = {}

# 执行次数
run_nums = 0


def get_res_sn_captcha():
    """获取验证码和sn的最终方法"""

    # 如果是生产环境，按照下面的逻辑走，先请求数据，再调用ocr识别
    if os.environ["ENV"] == "prod":
        global run_nums

        # 判断第一次执行的时候和失败重试的时候才会执行下面的获取验证码和sn的逻辑
        if not sn_captcha_text or run_nums % 2 == 0:
            sn,image = get_auth_captcha()
            captcha = dddd_ocr_text(image)
            sn_captcha_text["sn"] = sn
            sn_captcha_text["captcha"] = captcha

        run_nums += 1

        return sn_captcha_text

    # 测试环境按照下面的执行逻辑进行执行
    elif os.environ["ENV"] == "test":
        sn = get_auth_captcha()[0]
        # captcha = dddd_ocr_text(image)
        sn_captcha_text["sn"] = sn
        sn_captcha_text["captcha"] = "aaaa"
        return sn_captcha_text


if __name__ == '__main__':
    image = ""
    # text = dddd_ocr_text(image)
    # print(text)

    str1 = "dddd_ocr_text(image)"
    print(str1)
    print(eval(str1))

    # print(get_auth_captcha())
    print(get_res_sn_captcha())
    print(get_res_sn_captcha())